package com.base.pig.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.base.pig.entity.ScConfigAddress;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @ProjectName 图片转换
 * @Package com.pig4cloud.pig.admin.config
 * @ClassName Base64Utils
 * @Description
 * @Company lab
 * @Author zhangzhy
 * @Date 2020/3/26 15:18
 * @UpdateUser
 * @UpdateDate
 * @UpdateRemark
 * @Version 1.0.0
 */
@Slf4j
@Service
public class Base64Util {

    @Autowired
    private ScConfigAddress scConfigAddress;

    /**
     * 图片转化成base64字符串
     * @param imgPath
     * @return
     */
    public String fileToBase64(String imgPath) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        // 返回Base64编码过的字节数组字符串
        String encode = null;
        File file = new File(imgPath);
        if(file.exists()){
            encode = Base64.encode(file);
        }
        return encode;
    }

    /**
     * base64字符串转化成图片
     *
     * @param imgData
     *            图片编码
     * @param imgFilePath
     *            存放到本地路径
     * @return
     * @throws IOException
     */
    public boolean base64ToFile(String imgData, String imgFilePath, String imgFileName) throws IOException { // 对字节数组字符串进行Base64解码并生成图片
        // 图像数据为空
        if (imgData == null){
            return false;
        }
        // 如果文件夹不存在就创建
        File file = new File(imgFilePath);
        if(!file.exists()){
            file.mkdirs();
        }
        File filePath = new File(imgFilePath+imgFileName);
        Base64.decodeToFile(imgData,filePath);
        return true;
    }

    /**
     * @Title SaveImgs
     * @Description
     * @param userDto :
     * @return com.pig4cloud.pig.admin.api.entity.SysUser
     * @author zhangzhy
     * @date 2020/4/30 14:46
     */
    /*
    @SneakyThrows
    public SysUser SaveImgs(UserDTO userDto){
        SysUser sysUser = new SysUser();
        if(StrUtil.isNotBlank(userDto.getAvatar())){
            //判断注册时是否添加认证照片
            //拼接图片名称
            String avatarImgName = userDto.getPhone()+"."+userDto.getAvatarImgFrmat();
            //拼接存储路径
            String avatarImgPath =scConfigAddress.getAvatar();
            boolean avatar = this.base64ToFile(userDto.getAvatar(),avatarImgPath,avatarImgName);
            if(avatar){
                sysUser.setAvatar(avatarImgPath+avatarImgName);
            }
        }else {
            sysUser.setAvatar("");
        }
        if(StrUtil.isNotBlank(userDto.getWorkCardPath())){
            //拼接图片名称
            String workImgName = userDto.getPhone()+"."+userDto.getWordImgFrmat();
            //拼接存储路径
            String workImgPath =scConfigAddress.getWorkcard();
            boolean work = this.base64ToFile(userDto.getWorkCardPath(),workImgPath,workImgName);
            if(work){
                sysUser.setWorkCardPath(workImgPath+workImgName);
            }
        }else {
            sysUser.setWorkCardPath("");
        }
        return sysUser;
    }
*/
    /**
     * @Title fileExist  判断文件是否存在
     * @Description
     * @param path :
     * @return boolean
     * @author zhangzhy
     * @date 2020/5/7 15:22
     */
    public boolean fileExist(String path){
        File file = new File(path);
        boolean b = false;
        if(file.exists()){
            b = true;
        }
        return b;
    }

    /**
     * @Title downFile  下载文件
     * @Description
     * @param filePath :
     * @param response :
     * @return void
     * @author zhangzhy
     * @date 2020/5/7 16:13
     */
    //@SneakyThrows
    public void downFile(String filePath, HttpServletResponse response) throws IOException {
        if(StrUtil.isNotBlank(filePath)){
            File file = new File(filePath);
            if(file.exists()) {
                BufferedInputStream br = null;
                OutputStream out = null;
                // 取得文件名。
                try {
                    String filename = file.getName();
                    br = new BufferedInputStream(new FileInputStream(file));
                    byte[] buf = new byte[1024];
                    int len = 0;
                    response.reset();
                    response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename.trim(),"UTF-8") );
                    response.setHeader("Content-Length", ""+file.length());
                    response.setCharacterEncoding("UTF-8");
                    out = response.getOutputStream();
                    while ((len = br.read(buf)) > 0)
                        out.write(buf, 0, len);
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    br.close();
                    out.close();
                }

            }
        }
    }

    /***
     * @Title delete 删除文件及文件夹
     * @Description
     * @param file :
     * @return boolean
     * @author zhangzhy
     * @date 2020/5/21 14:36
     */
    // 删除文件夹
    public void deleteDirectory(File file) {
        // 表示该文件不是文件夹
        if (file.isFile()) {
            file.delete();
        } else {
            // 首先得到当前的路径
            String[] childFilePaths = file.list();
            for (String childFilePath : childFilePaths) {
                File childFile = new File(file.getAbsolutePath() + "/" + childFilePath);
                deleteDirectory(childFile);
            }
            file.delete();
        }
    }
}
